import os
import cv2
from skimage.feature import hog

def calculate_hog_features(image_path):
    """计算单张图片的HOG特征"""
    try:
        # 读取图片并转换为灰度图
        image = cv2.imread(image_path)
        if image is None:
            print(f"无法读取图片: {image_path}")
            return None
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 计算HOG特征
        features, hog_image = hog(gray, orientations=8, pixels_per_cell=(16, 16),
                                cells_per_block=(1, 1), visualize=True)
        return features
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {e}")
        return None

def scan_and_process_images(directory):
    """扫描目录并处理所有图片"""
    supported_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')
    
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(supported_extensions):
                image_path = os.path.join(root, file)
                print(f"处理图片: {image_path}")
                features = calculate_hog_features(image_path)
                if features is not None:
                    print(f"HOG特征维度: {len(features)}")

if __name__ == "__main__":
    image_directory = "image/"  # 图片目录
    if not os.path.exists(image_directory):
        os.makedirs(image_directory)
        print(f"目录 {image_directory} 不存在，已自动创建。请将图片放入该目录后重新运行程序。")
    else:
        scan_and_process_images(image_directory)